package com.agent.common.utils;

import com.agent.common.entity.TokenPair;
import com.agent.common.entity.UserContext;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.SecretKey;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPublicKey;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 统一JWT工具类
 */
@Slf4j
@Component
public class JwtUtils {

    // 配置参数
    @Value("${jwt.secret:defaultSecretKey}")
    private String secret;

    @Value("${jwt.access-expiration:1800}")
    private Long accessExpiration;

    @Value("${jwt.refresh-expiration:604800}")
    private Long refreshExpiration;

    // 密钥对象
    private SecretKey hmacKey;
    private KeyPair rsaKeyPair;

    // Spring 单例实例
    private static JwtUtils instance;

    @PostConstruct
    public void init() {
        // 初始化HMAC密钥
        this.hmacKey = Keys.hmacShaKeyFor(secret.getBytes());

        // 初始化RSA密钥对
        try {
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);
            this.rsaKeyPair = keyGen.generateKeyPair();
        } catch (Exception e) {
            throw new RuntimeException("Failed to generate RSA key pair", e);
        }

        // 设置静态实例
        instance = this;
    }

    // ================== 静态访问方法 ==================

    /**
     * 获取工具类实例（用于非Spring环境）
     */
    public static JwtUtils getInstance() {
        if (instance == null) {
            throw new IllegalStateException("JwtUtils has not been initialized by Spring");
        }
        return instance;
    }

    // ================== 基础方法 ==================

    /**
     * 生成HMAC-SHA令牌 对称加密
     */
    public String generateHmacToken(Long userId, String username, String membershipType) {
        return buildToken(userId, username, membershipType, accessExpiration, hmacKey, SignatureAlgorithm.HS256);
    }

    /**
     * 生成RSA令牌 非对称加密
     */
    public String generateRsaToken(UserContext userContext) {
        return buildToken(
                userContext.getUserId(),
                userContext.getUsername(),
                userContext.getMembershipType(),
                accessExpiration,
                rsaKeyPair.getPrivate(),
                SignatureAlgorithm.RS256
        );
    }

    /**
     * 生成令牌对（访问+刷新）
     */
    public TokenPair generateTokenPair(UserContext userContext) {
        return new TokenPair(
                generateRsaToken(userContext),
                buildToken(
                        userContext.getUserId(),
                        userContext.getUsername(),
                        userContext.getMembershipType(),
                        refreshExpiration,
                        rsaKeyPair.getPrivate(),
                        SignatureAlgorithm.RS256
                )
        );
    }

    private String buildToken(Long userId, String username, String membershipType,
                              Long expiration, Object signingKey, SignatureAlgorithm algorithm) {
        return Jwts.builder()
                .claim("userId", userId)
                .claim("username", username)
                .claim("membershipType", membershipType)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith((java.security.Key) signingKey, algorithm)
                .compact();
    }

    // ================== 验证方法 ==================

    public boolean validateHmacToken(String token) {
        return validateToken(token, hmacKey);
    }

    public boolean validateRsaToken(String token) {
        return validateToken(token, rsaKeyPair.getPublic());
    }

    private boolean validateToken(String token, Object signingKey) {
        try {
            Jwts.parserBuilder()
                    .setSigningKey((java.security.Key) signingKey)
                    .build()
                    .parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            log.error("JWT validation error: {}", e.getMessage());
            return false;
        }
    }

    // ================== 用户信息提取 ==================

    /**
     * 从令牌提取用户上下文
     */
    public UserContext extractUserContext(String token, boolean isRsa) {
        Claims claims = extractAllClaims(token, isRsa);
        UserContext context = new UserContext();
        context.setUserId(claims.get("userId", Long.class));
        context.setUsername(claims.get("username", String.class));
        context.setMembershipType(claims.get("membershipType", String.class));
        context.setIsAdmin(claims.get("isAdmin", Boolean.class));
        return context;
    }

    /**
     * 提取声明信息
     */
    public <T> T extractClaim(String token, boolean isRsa, String claimName, Class<T> requiredType) {
        Claims claims = extractAllClaims(token, isRsa);
        return claims.get(claimName, requiredType);
    }

    private Claims extractAllClaims(String token, boolean isRsa) {
        return Jwts.parserBuilder()
                .setSigningKey(isRsa ? rsaKeyPair.getPublic() : hmacKey)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    // ================== 管理员令牌 ==================

    public String generateAdminToken(Long userId, String username) {
        return Jwts.builder()
                .claim("userId", userId)
                .claim("username", username)
                .claim("isAdmin", true)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + accessExpiration * 1000))
                .signWith(rsaKeyPair.getPrivate(), SignatureAlgorithm.RS256)
                .compact();
    }

    public boolean isAdminToken(String token) {
        try {
            Claims claims = extractAllClaims(token, true);
            return claims.get("isAdmin", Boolean.class);
        } catch (Exception e) {
            return false;
        }
    }

    // ================== JWK端点支持 ==================

    public Map<String, Object> getJwkSet() {
        RSAPublicKey publicKey = (RSAPublicKey) rsaKeyPair.getPublic();

        Map<String, Object> jwk = new HashMap<>();
        jwk.put("kty", "RSA");
        jwk.put("alg", "RS256");
        jwk.put("kid", "default-key");
        jwk.put("n", publicKey.getModulus().toString(16));
        jwk.put("e", publicKey.getPublicExponent().toString(16));
        jwk.put("use", "sig");

        return Collections.singletonMap("keys", Collections.singletonList(jwk));
    }
}